package com.mlnx.web.data.controller;


import com.alibaba.fastjson.JSON;
import com.mlnx.common.entity.Response;
import com.mlnx.common.entity.ResponseData;
import com.mlnx.data.pojo.vo.EcgHeartVo;
import com.mlnx.data.service.EcgDataService;
import com.mlnx.service.base.properties.MutilDeviceProperties;
import com.mlnx.service.common.enums.ResponseEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.shan.spring.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by amanda.shan on 2017/4/28.
 */
@Api(value = "心电数据接口", tags = {"心电数据接口"})
@RestController
@RequestMapping("mlnx_device/ecg")
public class EcgController extends BaseController {

    @Autowired
    private EcgDataService ecgStoreService;

    @Autowired
    private MutilDeviceProperties mutilDeviceProperties;


    @ApiOperation(value = "获取原始心电数据", notes = "")
    @RequestMapping(value = "/getEcg", method = {RequestMethod.POST, RequestMethod.GET})
    public void getEcg(Integer patientId, Long startTime, Long endTime, HttpServletResponse response) {

        getEcg(patientId, startTime, endTime, response, "src");
    }

    @ApiOperation(value = "获取加密心电数据", notes = "")
    @RequestMapping(value = "/getEncryEcg", method = {RequestMethod.POST, RequestMethod.GET})
    public void getEncryEcg(Integer patientId, Long startTime, Long endTime, HttpServletResponse response) {

        getEcg(patientId, startTime, endTime, response, "encry");
    }

    @ApiOperation(value = "获取滤波心电数据", notes = "")
    @RequestMapping(value = "/getFilterEcg", method = {RequestMethod.POST, RequestMethod.GET})
    public void getFilterEcg(Integer patientId, Long startTime, Long endTime, HttpServletResponse response) {

        getEcg(patientId, startTime, endTime, response, "filter");
    }

    @ApiOperation(value = "获取心率数据", notes = "")
    @GetMapping(value = "/getEcgHeart")
    public ResponseData<List<EcgHeartVo>> getEcgHeartVos(Integer patientId, Long startTime, Long endTime, Integer limit) {

        return result(ecgStoreService.getEcgHeartVos(startTime, endTime, patientId, limit));
    }

    private void getEcg(Integer patientId, Long startTime, Long endTime, HttpServletResponse response, String flag) {
        Response responseData = null;
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            if (patientId == null || startTime == null || endTime == null) {
                responseData = result(ResponseEnum.ParamError);
                response.getWriter().write(JSON.toJSONString(responseData));
            } else {

                if (flag.equals("src")) {
                    ecgStoreService.sendEcgData(patientId, startTime, endTime, response.getWriter());
                } else if (flag.equals("encry")) {
                    ecgStoreService.sendEncryEcgData(patientId, startTime, endTime, response.getWriter());
                } else if (flag.equals("filter")) {
                    ecgStoreService.sendFilterEcgData(patientId, startTime, endTime, response.getWriter());
                }
            }
        } catch (IOException e) {
            logger.error(e, "获取心电数据异常");
            responseData = result(ResponseEnum.FAILED);
        } finally {
            try {
                if (response.getWriter() != null) {
                    response.getWriter().close();
                }
            } catch (IOException e) {
                logger.error(e, "response.getWriter().close()");
            }
        }
    }

    @ApiOperation(value = "自动获取原始心电数据", notes = "")
    @RequestMapping(value = "/getAutoEcg", method = {RequestMethod.POST, RequestMethod.GET})
    public Response getAutoFilterEcg(@RequestParam Integer patientId,
                                     @RequestParam(required = false) Long token,
                                     @RequestParam Integer limit, HttpServletResponse servletResponse) {

        return getAutoFilterEcg(patientId, token, limit, servletResponse, "src");
    }

    @ApiOperation(value = "自动获取滤波心电数据", notes = "")
    @RequestMapping(value = "/getAutoFilterEcg", method = {RequestMethod.POST, RequestMethod.GET})
    public Response getAutoEcg(@RequestParam Integer patientId, @RequestParam(required = false) Long token,
                               @RequestParam Integer limit, HttpServletResponse httpServletResponse) {

        return getAutoFilterEcg(patientId, token, limit, httpServletResponse, "filter");
    }

    @ApiOperation(value = "自动获取加密心电数据", notes = "")
    @RequestMapping(value = "/getAutoEncryEcg", method = {RequestMethod.POST, RequestMethod.GET})
    public Response getEncryEcg(@RequestParam Integer patientId, @RequestParam(required = false) Long token,
                                @RequestParam Integer limit, HttpServletResponse httpServletResponse) {

        return getAutoFilterEcg(patientId, token, limit, httpServletResponse, "encry");
    }

    private Response getAutoFilterEcg(Integer patientId, Long token, Integer limit,
                                      HttpServletResponse servletResponse, String flag) {

        if (patientId == null || limit == null) {
            return result(ResponseEnum.ParamError);
        } else {

            if (token == null) {
                Integer requestEcgDelayTime = mutilDeviceProperties.getData().getRequestEcgDelayTime();
                token = System.currentTimeMillis() - requestEcgDelayTime;
            }

            List<Map> ecgs = null;
            if (flag.equals("src")) {
                ecgs = ecgStoreService.getEcg(patientId, token, limit);
            } else if (flag.equals("filter")) {
                ecgs = ecgStoreService.getFilterEcg(patientId, token, limit);
            } else if (flag.equals("encry")) {
                ecgs = ecgStoreService.getEncryEcg(patientId, token, limit);
            }

            if (ecgs.size() > 0) {
                servletResponse.setHeader("token", ecgs.get(ecgs.size() - 1).get("startTime") + "");
            } else {
                servletResponse.setHeader("token", token.toString());
            }

            return result(ecgs);
        }
    }


    @ApiOperation(value = "获取最新的心电数据", notes = "")
    @RequestMapping(value = "/getLastEcgTime", method = {RequestMethod.POST, RequestMethod.GET})
    public Response getLastEcgTime(Integer patientId, Long startTime, Integer limit) {
        Response response;
        if (patientId == null || limit == null) {
            response = result(ResponseEnum.ParamError);
        } else {
            response = new ResponseData(ecgStoreService.getLastEcgTime(patientId, startTime, limit));
        }
        return response;
    }
}
